package com.example.sandbox.controller.channel.uupay;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sandbox.controller.notice.PayComponent;
import com.example.sandbox.dto.AccountQueryRequest;
import com.example.sandbox.dto.Enum.Currency;
import com.example.sandbox.dto.MerchantRequest;
import com.example.sandbox.dto.domain.AccountBalance;
import com.example.sandbox.dto.domain.PayOrder;
import com.example.sandbox.mapper.AccountBalanceMapper;
import com.example.sandbox.mapper.PayOrderMapper;
import com.example.sandbox.util.AmountUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;

@Slf4j
@RestController
public class UupayPayOrderController {

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private AccountBalanceMapper accountBalanceMapper;
    @Autowired
    private PayComponent payComponent;
    @Autowired
    private Executor generalExecutor;

    @GetMapping("/api/v1/sandbox/order/simulatePaymentS/{payOrderId}")
    public String simulatePaymentS(@PathVariable("payOrderId") String payOrderId) throws IOException {
        if (StringUtils.isEmpty(payOrderId)){
            return "请传入订单号";
        }
        QueryWrapper<PayOrder> query = new QueryWrapper<>();
        query.eq("pay_order_id", payOrderId).eq("state", PayOrder.STATE_ING);
        PayOrder payOrder = payOrderMapper.selectOne(query);
        if (Objects.isNull(payOrder)){
            return "订单不存在或订单状态不在支付中";
        }
        payOrder.setState(PayOrder.STATE_SUCCESS);
        int isUpdated = payOrderMapper.update(payOrder, query);
        if (isUpdated > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("payOrderId", payOrder.getPayOrderId()); // 系统支付订单号
            dataMap.put("mchNo", payOrder.getMchNo()); // 商户号
            dataMap.put("mchOrderNo", payOrder.getMchOrderNo()); // 商户传入的订单号
            dataMap.put("amount", AmountUtil.convertCent2Dollar(payOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
            dataMap.put("currency", payOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
            dataMap.put("state", PayOrder.STATE_SUCCESS); // 支付订单状态
            dataMap.put("subject", payOrder.getSubject()); // 商品标题
            dataMap.put("body", payOrder.getBody()); // 商品描述
            dataMap.put("createdAt", payOrder.getCreatedAt().getTime() ); // 订单创建时间, 13位时间戳
            dataMap.put("successTime", System.currentTimeMillis() ); // 订单支付成功时间, 13位时间戳
            dataMap.put("reqTime", System.currentTimeMillis() ); // 订单支付成功时间, 13位时间戳
            generalExecutor.execute(() -> {
                try {
                    payComponent.notifyPaymentPay(dataMap, payOrder.getNotifyUrl(), "application/x-www-form-urlencoded");
                } catch (IOException e) {
                    log.error("uu - 支付失败通知异常 url:{}", payOrder.getNotifyUrl());
                    throw new RuntimeException(e);
                }
            });
            return "操作成功,支付成功";
        }
        return "操作失败";
    }

    @GetMapping("/api/v1/sandbox/order/simulatePaymentF/{payOrderId}")
    public String simulatePaymentF(@PathVariable("payOrderId") String payOrderId) throws IOException {
        if (StringUtils.isEmpty(payOrderId)){
            return "请传入订单号";
        }
        QueryWrapper<PayOrder> query = new QueryWrapper<>();
        query.eq("pay_order_id", payOrderId).eq("state", PayOrder.STATE_ING);
        PayOrder payOrder = payOrderMapper.selectOne(query);
        if (Objects.isNull(payOrder)){
            return "订单不存在或订单状态不在支付中";
        }
        payOrder.setState(PayOrder.STATE_FAIL);
        int isUpdated = payOrderMapper.update(payOrder, query);
        if (isUpdated > 0) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("payOrderId", payOrder.getPayOrderId()); // 系统支付订单号
            dataMap.put("mchNo", payOrder.getMchNo()); // 商户号
            dataMap.put("mchOrderNo", payOrder.getMchOrderNo()); // 商户传入的订单号
            dataMap.put("amount", AmountUtil.convertCent2Dollar(payOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
            dataMap.put("currency", payOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
            dataMap.put("state", PayOrder.STATE_FAIL); // 支付订单状态
            dataMap.put("subject", payOrder.getSubject()); // 商品标题
            dataMap.put("body", payOrder.getBody()); // 商品描述
            dataMap.put("createdAt", payOrder.getCreatedAt().getTime() ); // 订单创建时间, 13位时间戳
            dataMap.put("successTime", System.currentTimeMillis() ); // 订单支付成功时间, 13位时间戳
            dataMap.put("reqTime", System.currentTimeMillis() ); // 订单支付成功时间, 13位时间戳
            generalExecutor.execute(() -> {
                try {
                    payComponent.notifyPaymentPay(dataMap, payOrder.getNotifyUrl(), "application/x-www-form-urlencoded");
                } catch (IOException e) {
                    log.error("uu - 支付失败通知异常 url:{}", payOrder.getNotifyUrl());
                    throw new RuntimeException(e);
                }
            });
            return "操作成功,支付失败";
        }
        return "操作失败";
    }

    @PostMapping("/api/v1/pay/brazil/queryOrder")
    public Map queryOrder(@RequestBody MerchantRequest request) {

        if (StringUtils.isEmpty(request.getPayOrderId()) && StringUtils.isEmpty(request.getMchOrderNo())){
            Map map = new HashMap();
            map.put("提示", "商户订单号，与支付订单号不可同时为空");
            return map;
        }
        String mchOrderNo = (request.getMchOrderNo() != null && !request.getMchOrderNo().isEmpty()) ? request.getMchOrderNo() : "";
        String payOrderId = (request.getPayOrderId() != null && !request.getPayOrderId().isEmpty()) ? request.getPayOrderId() : "";
        QueryWrapper<PayOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mch_no", request.getMchNo());

        queryWrapper.eq(StringUtils.isNotEmpty(payOrderId),"pay_order_id", payOrderId);
        queryWrapper.eq(StringUtils.isNotEmpty(mchOrderNo),"mch_order_no", mchOrderNo);
        PayOrder payOrder = payOrderMapper.selectOne(queryWrapper);
        if (Objects.isNull(payOrder)){
            Map map = new HashMap();
            map.put("提示", "订单不存在");
            return map;
        }
        // 创建一个 Map 用于存放响应数据
        Map<String, Object> responseMap = new HashMap<>();

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("payOrderId", payOrder.getPayOrderId()); // 系统支付订单号
        dataMap.put("mchNo", payOrder.getMchNo()); // 商户号
        dataMap.put("mchOrderNo", payOrder.getMchOrderNo()); // 商户传入的订单号
        dataMap.put("amount", AmountUtil.convertCent2Dollar(payOrder.getAmount(), Currency.BRL.getCurrency())); // 支付金额（3位小数）
        dataMap.put("currency", payOrder.getCurrency()); // 三位货币代码, 巴西币 BRL
        dataMap.put("state", payOrder.getState()); // 支付订单状态
        dataMap.put("subject", payOrder.getSubject()); // 商品标题
        dataMap.put("body", payOrder.getBody()); // 商品描述
        dataMap.put("createdAt", payOrder.getCreatedAt().getTime() ); // 订单创建时间, 13位时间戳
        dataMap.put("successTime", System.currentTimeMillis() ); // 订单支付成功时间, 13位时间戳

        responseMap.put("code", 0);
        responseMap.put("msg", "SUCCESS");
        responseMap.put("data", dataMap);
        responseMap.put("sign", "557B1724497D5792813CA573D96A23DB"); // 这里的签名根据实际情况生成
        return responseMap;
    }

    @PostMapping("/api/v1/pay/brazil/queryMchAccount")
    public Map queryMchAccount(@Validated @RequestBody AccountQueryRequest request) {

        QueryWrapper<AccountBalance> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_type", "1");
        queryWrapper.eq("mch_no", request.getMchNo());
        queryWrapper.eq("currency", request.getCurrency());
        AccountBalance accountBalance = accountBalanceMapper.selectOne(queryWrapper);
        if (Objects.isNull(accountBalance)){
            Map map = new HashMap();
            map.put("提示", "币种钱包不存在");
            return map;
        }

        // 创建一个 Map 用于存放响应数据
        Map<String, Object> responseMap = new HashMap<>();

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("balance", AmountUtil.convertCent2Dollar(accountBalance.getAmount(), request.getCurrency())); // 余额
        dataMap.put("frozenBalance", AmountUtil.convertCent2Dollar(accountBalance.getFrozenAmount(), request.getCurrency())); // 冻结余额
        dataMap.put("currency", request.getCurrency()); // 订单创建时间, 13位时间戳

        responseMap.put("code", 0);
        responseMap.put("msg", "SUCCESS");
        responseMap.put("data", dataMap);
        responseMap.put("sign", "557B1724497D5792813CA573D96A23DB"); // 这里的签名根据实际情况生成
        return responseMap;
    }
}
